﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.NetworkInformation;
using System.Text;
using System.Threading.Tasks;

class PortHelper
{

    #region 指定类型的端口是否已经被使用了
    /// <summary>
    /// 指定类型的端口是否已经被使用了
    /// </summary>
    /// <param name="port">端口号</param>
    /// <param name="type">端口类型</param>
    /// <returns></returns>
    public static bool portInUse(int port, PortType type)
    {
        bool flag = false;
        IPGlobalProperties properties = IPGlobalProperties.GetIPGlobalProperties();
        IPEndPoint[] ipendpoints = null;
        if (type == PortType.TCP)
        {
            ipendpoints = properties.GetActiveTcpListeners();
        }
        else
        {
            ipendpoints = properties.GetActiveUdpListeners();
        }
        foreach (IPEndPoint ipendpoint in ipendpoints)
        {
            if (ipendpoint.Port == port)
            {
                flag = true;
                break;
            }
        }
        ipendpoints = null;
        properties = null;
        return flag;
    }
    #endregion

    public static int PortTcpConnection(int port)
    {
        IPGlobalProperties properti = IPGlobalProperties.GetIPGlobalProperties();
        var tcps = properti.GetActiveTcpConnections().ToList();

        var list = tcps.Where(f => f.LocalEndPoint.Port == port);

        var iplist = list.GroupBy(f => f.RemoteEndPoint.Address);
        return iplist.Count();
    }

}

#region 端口枚举类型
/// <summary>
/// 端口类型
/// </summary>
enum PortType
{
    /// <summary>
    /// TCP类型
    /// </summary>
    TCP,
    /// <summary>
    /// UDP类型
    /// </summary>
    UDP
}
#endregion